<script type="text/javascript">
window.UMEDITOR_HOME_URL = "${request.contextPath}/assets/plugins/umeditor-v1.2.2/";
</script>
<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" maxHttpHeaderSize="65536" maxPostSize="4194304"  
               URIEncoding="UTF-8"/>
<div class="main_fr_search over mb10">
	<form id="search_submit" class="form-inline">
		<div class="good_top22">
			<span class="good_top021">条件查询</span>
		</div>
		<div class="main_fr_search_cx">
			标题<input name="articles.title" placeholder="请输入标题名称" type="text"
				class="form-control" style="width: 200px;" /> 状态
				<select
				name="articles.status" class="form-control" style="width: 200px;">
				<option value="">请选择</option>
				<option value="2">发布</option>
				<option value="1">草稿</option>
				<option value="3">隐藏</option>
            </select>
            @@ if (isNotEmpty(parameter.kindDicType)) {
             <select id="status" name="articles.model_type_dic" class="form-control" style="width:200px;">
				<option value="" selected="selected">选择分类</option>
				<#dicList typeId="${parameter.kindDicType}";dicList>
				@@for(r in dicList) {
	           		<option value="${r.id}">${r.content}</option>
	            @@ }
	            </#dicList>
			</select>
			@@ }
			<input type="button" onclick="search(1);" class="search_an01 anbg"
				value="查询">
		</div>
	</form>
</div>
<div class="sh_search over mb10">
	<div class="over sh_search_table">

		<div class="over mb10" style="position: relative;">
			<div class="good_top22" style="margin-bottom: 0px;">
				<span class="good_top021">内容列表</span> <span class="good_top022">
					@@if (ac(session.userId, 'articles/add')){
						@@if (parameter.isFinal == '0') {
						<input type="button" onclick="update(0);" class="search_an01" value="新增">
						@@ } else {
						<mark>当前栏目下不能直接添加内容</mark>
						@@ }
					@@ }
				</span>
			</div>
		</div>
	</div>
	<table class="table table-bordered table-hover">
		<thead class="table_heaer">
			<tr class="text-center">
				<th>编号</th>
				<th class="col-xs-5">文章名称</th>
				<th>所属栏目</th>
				<th>访问量</th>
				<th>状态</th>
				<th>操作</th>
			</tr>
		</thead>
		<tbody id="projectTable">
		</tbody>
	</table>

</div>
<div id="pages" class="text-right"></div>

<!--  弹出层div-->
<div id="addFormDiv" class="hide" style="padding-top:15px;">
	<form class="form-horizontal" id="addForm">
		<div class="form-group">
			<label for="exampleInputEmail2" class="col-sm-2 control-label">所属栏目</label>
			<div class="col-sm-9" id="column_name">
			</div>
		</div>
		@@ if (!isEmpty(parameter.kindDicType)) {
		<div class="form-group">
			<label for="exampleInputEmail2" class="col-sm-2 control-label">分类</label>
			<div class="col-sm-9">
				<select id="status" name="articles.model_type_dic" class="form-control" style="width:200px;">
				<#dicList typeId="${parameter.kindDicType}";dicList>
				@@for(r in dicList) {
	           		<option value="${r.id}">${r.content}</option>
	            @@ }
	            </#dicList>
	            </select> 
            </div>
		</div>
        @@ }
		<input type="hidden" id="id" name="articles.id">
		<div class="form-group">
			<label for="inputEmail3" class="col-sm-2 control-label">文章标题</label>
			<div class="col-sm-9">
				<input type="text"  class="form-control" id="title" placeholder="请输入文章标题" name="articles.title" minlength="2"  maxlength="30" required>
			</div>
		</div>
		<div class="form-group">
			<label for="exampleInputEmail2" class="col-sm-2 control-label">文章摘要</label>
			<div class="col-sm-9">
				<textarea rows="5" style="width:100%" id="summary" name="articles.summary" placeholder="请输入文章摘要" minlength="2"  maxlength="90" required></textarea>
			</div>
		</div> 
		<div class="form-group" id="image_content">
		    <label for="exampleInputEmail2" class="col-sm-2 control-label">封面图片</label>
			<div class="col-sm-9">
			    <div style="float:left;">
			        <div class="files" id="image_path"></div>
		            <div style="clear:both;"></div><div class="up_progress"><div class="progress-bar"></div></div>
		            <div style="clear:both;"></div>
			    </div>
			    <div style="float:left;" class="fileinput_a" id="image_fileDiv">
				<input class="fileinput_input" type="file" value="浏览" id="imageupload" name="image_files" data-url="upload/getFileUpload" multiple/>
                </div>
                <div style="float:left;" >
          		 上传图片要求：格式（gif，jpe?g，png）最大为 2M
			    </div>
			     <br><br><br><br>
	     	<div id="tishi" class="hide"><font color="red">请上传图片！</font></div>
	         </div>
	    </div>
	    <div class="form-group">
			<label for="exampleInputEmail2" class="col-sm-2 control-label">文章内容</label>
			<div class="col-sm-9">
				<!-- <textarea rows="5" cols="90%" placeholder="请输入文章内容"></textarea> -->
				<script id="content" type="text/plain"></script>
			</div>
		</div> 
	    <!-- <div class="form-group">
			<label for="exampleInputEmail2" class="col-sm-2 control-label">关键词</label>
			<div class="col-sm-9">
				<input type="text" class="form-control" id="keywords" placeholder="请输入关键词" name="articles.keywords" minlength="1"  maxlength="10" required>
			</div>
		</div>  -->
		<div class="form-group">
			<label for="exampleInputEmail2" class="col-sm-2 control-label">状态</label>
			<div class="col-sm-9">
			<select id="status" name="articles.status" class="form-control" style="width:200px;">
          		<option value="2">发布</option>
          		<option value="1">草稿</option>
          		<option value="3">隐藏</option>
          	</select> 
			</div>
		</div>
		 
		<div class="form-group">
		<label for="exampleInputEmail2" class="col-sm-2 control-label"></label>
			<div class="col-sm-9">
			<button type="submit" class="btn btn-success">立即提交</button>
			<button type="reset" class="btn btn-default">重置</button>
			</div>
		</div>
		
	</form>
</div>
<!-- 在这里引入本页面需要的js -->
<script type="text/javascript" charset="utf-8" src="assets/plugins/umeditor-v1.2.2/umeditor.min.js"></script>
<script type="text/javascript" charset="utf-8" src="assets/plugins/umeditor-v1.2.2/umeditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="assets/plugins/umeditor-v1.2.2/lang/zh-cn/zh-cn.js"></script>
<script type="text/javascript">
	var um = UM.getEditor('content');
    um.setWidth("100%");
    $(".edui-body-container").css("width", "97%");
</script>
<script>
function userList(data) {
	var dataStr = "";
	$.each(data.list, function(i, v) {
		dataStr += '<tr id=col_' + v.id + '>';
		dataStr += '<td>' + ((data.pageNumber-1)*data.pageSize+i+1) + '</td>';
		dataStr += '<td><a target="_blank" href="detail?columnId=' + v.column_id + '&contentId=' + v.id  + '">' + v.title + '</a></td>';
		dataStr += '<td>' + v.name + '</td>';
		dataStr += '<td>' + v.view_count + '</td>';
		if(v.status==1){
			dataStr += '<td>草稿</td>';
		}else if(v.status==2) {
			dataStr += '<td>发布</td>';
		}else if(v.status==3) {
			dataStr += '<td>隐藏</td>';
		}
		dataStr += '<td>';
			@@if (ac(session.userId, 'articles/update')){
				/* dataStr += '<a href="javaScript:update(' + v.id + ');" class="btn btn-primary">' + '审核' + '</a>'; */
				dataStr += '<a href="javaScript:update(' + v.id + ');" class="btn btn-default">' + '编辑' + '</a>';
			@@}
			@@if (ac(session.userId, 'articles/fujian')){
				dataStr += '<a href="javaScript:fujianList(' + v.id + ');" class="btn btn-default">' + '附件' + '</a>';
			@@}
			@@if (ac(session.userId, 'articles/upRow')){
				dataStr += '<a href="javaScript:upRow(' + v.id + ',' + v.column_id + ');" class="btn btn-default" title="下移"><i class="glyphicon glyphicon-arrow-down"></i></a>';
			@@}
			@@if (ac(session.userId, 'articles/downRow')){
				dataStr += '<a href="javaScript:downRow(' + v.id + ',' + v.column_id + ');"class="btn btn-default" title="上移"><i class="glyphicon glyphicon-arrow-up"></i></a>';
			@@}
			
		dataStr += '</td>'; 
		 
		dataStr += '</tr>';
	});
	$("#projectTable").html(dataStr);
	$("#projectTable .deleteButton").click(function() {
		clickDelete($(this));
		return false;
	})
}
var cc=1;
function pageChange(curr) {
	$.get("articles/page?articles.column_id=${parameter.columnId}&curr="+curr, $("#search_submit").serialize(), function(data) {
		if (data.code == 0) {
			if (data.content.totalRow == 0) {
				layer.msg("数据为空");
				return;
			}
			userList(data.content);
			laypage({
			    cont: $('#pages'), //容器。值支持id名、原生dom对象，jquery对象,
			    pages: data.content.totalPage, //总页数
			    skip: true, //是否开启跳页
			    skin: '#4599e0',
			    curr: data.content.pageNumber,
			    groups: 3, //连续显示分页数
			    jump: function(obj, first) {
					if(!first){ //一定要加此判断，否则初始时会无限刷新
						cc=obj.curr;
						pageChange(obj.curr);
					}
			    }
			});
		} else {
			layer.msg("请求失败，请刷新");
		}
	});
}
pageChange(1);
function search(curr){
	if(curr != 1){
		curr=cc;
	}
	pageChange(curr);
}
var index;
var validator;
$().ready(function() {
	 validator = $("#addForm").validate({
	 	submitHandler:function(form){
	    	var img = $("#img").val();
	    	if(img==null || img ==""){
	    		$("#tishi").removeClass("hide");
    			return false;
	    	}else{
	    		$("#tishi").addClass("hide");
	    	}
	    	var content = um.getContent();
	    	if(content==null || content=="" || content == "<p><br></p>"){
	    		layer.msg("内容不能为空！");
	    		return false;
	    	}
	    	var id = $("#id").val();
	    	var url = "articles/add";
	    	if(id != null && id != ""){
	    		url = "articles/update";
	    	} 
	 		var params = $("#addForm").serializeObject(); //将表单序列化为JSON对象
	 		params.editorValue = content;
	    	$.post(url + "?articles.column_id=" + zTreeObj.getSelectedNodes()[0].id, params, function(data){
	    		if(data.code==0){
	    			layer.msg("保存成功！");
	    			layer.close(index);
	    			search(cc);
	    		}else{
	    			layer.msg("标题名称不能重复！");
	    			return false;
	    		}
	    	}) 
	        }    
	    });
	    $("#reset").click(function() {
	        validator.resetForm();
	    });
	});
	
$.fn.serializeObject = function() {  
     var o = {};  
     var a = this.serializeArray();  
     $.each(a, function() {  
         if (o[this.name]) {  
             if (!o[this.name].push) {  
                 o[this.name] = [ o[this.name] ];  
             }  
             o[this.name].push(this.value || '');  
         } else {  
             o[this.name] = this.value || '';  
         }  
     });  
     return o;  
 } 	
function update(id) {
	var tit = "新增文章信息";
	$("#column_name").html(zTreeObj.getSelectedNodes()[0].name);
	if(id != 0){
		$.post("articles/getInfo",{id:id},function(data){
			if(data.code==0){
				for (var key in data.content){
					$("#"+key).val(data.content[key]);
				}
			$("#content").html(data.content['main_body']);
			var imgshow = '<div class="images_zone"><input type="hidden" id ="img" name="articles.img_path" value="'+data.content['img_path']+'" /><span><img src="'+data.content['img_path']+'"  /></span><a href="javascript:;">删除</a></div>';
	   	     $(".files").empty();
	   	     jQuery('#image_path').append(imgshow);	//将上传之后的图片放到image_path容器中
	   	     $("#image_fileDiv").addClass("hide");

	   	  if(data.content['img_path']==null || data.content['img_path']==""){
						$("#image_path").empty();
						$("#image_fileDiv").removeClass("hide");
			  }
			}else{
				layer.msg("获取信息失败！");
				return false;
			}
		})
		tit = "修改文章信息";
	}else{
		document.getElementById("addForm").reset();
		$("#id").val("");
		$("#image_path").empty();
		$("#image_fileDiv").removeClass("hide");
		 um.setContent("<p><br></p>");
	} 
 	$("#addFormDiv").removeClass("hide");
	index=layer.open({
		type : 1,
		area: ['50%','85%'],
		title : tit,
		content : $("#addFormDiv"),
		
		cancel: function(index, layero) {
			 validator.resetForm();//// 重置表单验证提示
			    
			$("#addFormDiv").addClass("hide");
			layer.close(index);
		} 
	})
};
function fujianList(id){
	layer.open({
		type : 2,
		area: ['80%', '80%'],
		offset: 0,
		shift: 1,
		scrollbar: false,
		title: '附件管理',
		content : 'articles/fujian?id='+id,
	})
	return ;
}
function clickDelete(obj) {
	// 给删除按钮注册事件
	// 获取当前记录的信息写入
	if(confirm("确定要删除该文章吗？")){
		var recordId = obj.attr("recordId");
		$.get("articles/del", {"id":recordId}, function(data) {
			if (data.code == 0) {
				obj.closest("tr").remove();
				layer.msg("删除成功！");
			}else{
				layer.msg("删除失败！");
				return false;
			} 
		})
	}
}
function upRow(id,column_id){
	$.post("articles/upRow?id="+id,{column_id:column_id},function(data){
		if (data.code == 0) {
			search();
		} else {
			layer.msg("当前文章已经是最后一位！");
		}
   	});
}
function downRow(id,column_id){
	$.post("articles/downRow?id="+id,{column_id:column_id},function(data){
		if (data.code == 0) {
			search();
		}else{
			layer.msg("当前文章已经在第一位！");
		}
   	});
}
</script>
<script>
/* 图片上传*********************************************************** */
$("#imageupload").fileupload({
	dataType: 'json',
	maxFileSize : 5000000000, // 5 G，文件大小,这里没有用，在acceptFileSize限制文件大小
    add: function (e, data) {//将要上传的文件名显示在一个元素节点上：你可以经常要将上传的文件显示到特定的元素上，这个可以通过add回调函数来实现：
	
	var select = $("#type").val();//获取选择框数据
	var uploadErrors = [];//创建一个包含错误类型的数组
 		var acceptFileTypes;//设置上传文件的类型
 		var acceptFileSize;
 		select = 2;
 		if (select==2) {
 			acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;
 			acceptFileSize = 2*1024*1024;//2M
		}
 		//alert(1);
 		//console.log(data);
 		if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
 		   uploadErrors.push('文件类型不正确！');
 		  }
 		if(data.originalFiles[0]['size'] > acceptFileSize) {
 		   uploadErrors.push('文件太大了！');
 		  }
 		/* ----------------------------------------------------------------------------------------------------- */
   	 var files=data.files;
           for (var i = 0; i < files.length; i++) {
               var file = files[i];
               var reader = new FileReader();
               var ret = [];
               reader.onload = function(theFile) {
                   var image = new Image();
                   image.onload = function() {
                       width_fileInputId=this.width;
                       height_fileInputId=this.height;
                	   if(uploadErrors.length > 0) {
                 		   alert(uploadErrors.join("\n"));
                 		   return false;
                 		  }else {
                 			 var numItems = $('.files .images_zone').length;//获取图片容器内的图片数量
                 			 if (select==2) {
                 			if(numItems>1){
                 				alert('每次只能上传1张');
                 				return false;
                 			}
                 			}
                 	 		//**************************自动上传**************************
                 	 		$('.up_progress .progress-bar').css('width','0px');//给进度条添加样式
                		    $('.up_progress').show();//显示进度条
                		    $('.up_progress .progress-bar').html('Uploading...');//显示进度条文字
                		    data.submit(); 
                		    //**************************自动上传**************************
                		   
                		}
                   };
                   image.src = theFile.target.result;
               }
               reader.readAsDataURL(file);
           }
   	/* ------------------------------------------------------------------------------------------------- */
 		
    },
    done: function (e, data) {//完成之后的回调函数
	var d = data.result;//获取的数据必须转为data.result才可以使用！！！
	var select = $("#type").val();
	select = 2;
	$('.up_progress').hide();
	$('.upl').remove();
        //var d = data.result;
        if (select==2) {
    	 var imgshow = '<div class="images_zone"><input type="hidden" id="img" name="articles.img_path" value="upload/image/'+d.content+'" /><span><img src="upload/image/'+d.content+'"  /></span><a href="javascript:;">删除</a></div>';
    	 $(".files").empty();
    	 jQuery('#image_path').append(imgshow);	//将上传之后的图片放到image_path容器中
    	 $("#image_fileDiv").addClass("hide");
 	 		 $("#image_reset").removeClass("hide");
        }
    },
    progressall: function (e, data) {//所有文件的总体上传进度(progressall)显示
	console.log(data);
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $('.up_progress .progress-bar').css('width',progress + '%');
    }
});
//图片删除
$('.files').on({
	mouseenter:function(){
		$(this).find('a').show();
	},
	mouseleave:function(){
		$(this).find('a').hide();
	},
},'.images_zone');
$('.files').on('click','.images_zone a',function(){
	$(this).parent().remove();
	$("#image_fileDiv").removeClass("hide");
});
function preview(){
	layer.msg("请稍后！");	
}
</script>